package com.hitcoder.chat.ui.widget

import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

/**
 * 基于[SwipeRefreshLayout]封装的下拉刷新、上拉加载更多控件
 */
class RefreshAndLoadLayout(context: Context, attrs: AttributeSet?) :
    SwipeRefreshLayout(context, attrs) {

    private var recyclerView: RecyclerView? = null
    private var isLoading = false


    constructor(context: Context) : this(context, null)

    override fun onFinishInflate() {
        super.onFinishInflate()
        if (childCount == 0) return
        for (i in 0 until childCount) {
            val childView = getChildAt(i)
            if (childView is RecyclerView) {
                recyclerView = childView
            }
        }
    }

    fun setOnLoadMoreListener(listener: () -> Unit) {
        recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var lastItem = 0
            var firstItem = 0
            var totalItemCount = 0

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastItem == totalItemCount - 1
                    && !isLoading
                ) {
                    isLoading = true
                    //触发加载更多操作
                    listener()
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                when (val layoutManager = recyclerView.layoutManager) {
                    is GridLayoutManager -> {
                        firstItem = layoutManager.findFirstCompletelyVisibleItemPosition()
                        lastItem = layoutManager.findLastCompletelyVisibleItemPosition()
                        if (lastItem == -1) lastItem = layoutManager.findLastVisibleItemPosition()
                        totalItemCount = layoutManager.itemCount
                    }
                    is LinearLayoutManager -> {
                        firstItem = layoutManager.findFirstCompletelyVisibleItemPosition()
                        lastItem = layoutManager.findLastCompletelyVisibleItemPosition()
                        if (lastItem == -1) lastItem = layoutManager.findLastVisibleItemPosition()
                        totalItemCount = layoutManager.itemCount
                    }
                    is StaggeredGridLayoutManager -> {
                        val lastPositions = IntArray(layoutManager.spanCount)
                        layoutManager.findLastCompletelyVisibleItemPositions(lastPositions)
                        lastItem = findMax(lastPositions)
                        firstItem = layoutManager.findFirstVisibleItemPositions(lastPositions)[0]
                        totalItemCount = layoutManager.itemCount
                    }
                }

            }

            //To find the maximum value in the array
            private fun findMax(lastPositions: IntArray): Int {
                var max = lastPositions[0]
                lastPositions.forEach { if (it > max) max = it }
                return max
            }
        })

    }

    fun loadMoreComplete() {
        isLoading = false
    }

}